import glob
import string

import zhon.hanzi
from pyparsing import Group, OneOrMore, Word, ZeroOrMore, alphanums, alphas


def search(startdir):
    result = [filename for filename in glob.glob(
        f'{startdir}\**', recursive=True) if r'.md' in filename]
    return result


def punction():
    hanzi = zhon.hanzi.punctuation
    punctuation = string.punctuation
    return hanzi.join(punctuation)


def MarkdownPattern():

    # 列出汉字
    unicodePrintables = ''.join(chr(c) for c in range(0x4e00, 0x9fa5)
                                if not chr(c).isspace())
    asciiword = Word(alphas+alphanums+"/:!.-_*&=?%+~#,")

    punstr = punction()
    punstr = punstr.replace(']', '').join("…？™")
    utfword = Word(alphas+alphanums+unicodePrintables + punstr)

    punstr = punction()
    punstr = punstr.replace('[', '')
    prefix = Word(alphas+alphanums+unicodePrintables+ punstr)
    postfix = Word(alphas+alphanums+unicodePrintables+",")

    titleline = "[" + Group(OneOrMore(utfword)).set_results_name("title") + "]"
    hyperline = "(" + Group(OneOrMore(asciiword)).set_results_name("url") + ")"
    return ZeroOrMore(prefix) + titleline + hyperline + ZeroOrMore(postfix)

def UrlPattern():

    # 列出汉字
    unicodePrintables = ''.join(chr(c) for c in range(0x4e00, 0x9fa5)
                                if not chr(c).isspace())
    asciiword = Word(alphas+alphanums+"/:!.-_*&=?%+~#,()")

    punstr = punction()
    punstr = punstr.replace(']', '').join("…？™")
    utfword = Word(alphas+alphanums+unicodePrintables + punstr)

    punstr = punction()
    punstr = punstr.replace('<', '')
    prefix = Word(alphas+alphanums+unicodePrintables+ punstr)
    postfix = Word(alphas+alphanums+unicodePrintables+",")

    hyperline = "<" + Group(OneOrMore(asciiword)).set_results_name("url") + ">"
    return ZeroOrMore(prefix) + hyperline + ZeroOrMore(postfix)


def extract_url(filename, resultfilename):
    pattern = UrlPattern()

    def markdown(inputstr) -> str:
        inputstr = inputstr.replace("\u200b", "").replace('\xa0', "")
        print(inputstr)
        result = pattern.parseString(inputstr)
        return f"{result.url[0]}\r"

    with open(filename, 'r', encoding='utf-8') as myfile:
        result = [markdown(line)
                  #   for line in myfile.readlines() if len(line) > 2 and 'http' in line and '](http' in line]
                  for line in myfile.readlines() if len(line) > 2 and '<http' in line]

    # 输出结果
    with open(resultfilename, 'a', encoding='utf-8') as myfile:
        myfile.writelines(result)

def extract_url_markdown(filename, resultfilename):
    pattern = MarkdownPattern()

    def markdown(inputstr) -> str:
        inputstr = inputstr.replace("\u200b", "").replace('\xa0', "")
        print(inputstr)
        result = pattern.parseString(inputstr)
        return f"{result.title[0]},{result.url[0]}\r"

    with open(filename, 'r', encoding='utf-8') as myfile:
        result = [markdown(line)
                  #   for line in myfile.readlines() if len(line) > 2 and 'http' in line and '](http' in line]
                  for line in myfile.readlines() if len(line) > 2 and '](http' in line]

    # 输出结果
    with open(resultfilename, 'a', encoding='utf-8') as myfile:
        myfile.writelines(result)
